package com.irisking.server.utils;

import java.util.Arrays;

public class ConvertUtil {

    public static int toInt(byte[] b) {
        int res = 0;
        for (int i = 0; i < b.length; i++) {
            res += (b[i] & 0xff) << (i * 8);
            //res += (b[i] & 0xff) << ((3-i)*8);
        }
       // System.out.println("toInt before:" +  Arrays.toString(b) + ",after:" + res);
        return res;
    }

    public static short toShort(byte[] b) {
        short res = 0;
        for (int i = 0; i < b.length; i++) {
            res += (b[i] & 0xff) << (i * 8);
            //res += (b[i] & 0xff) << ((3-i)*8);
        }
        //System.out.println("toShort before:" +  Arrays.toString(b) + ",after:" + res);
        return res;
    }

    public static byte[] intToByte(int n) {
        //System.out.println("covert:" + n);
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (n & 0xff);
        bytes[1] = (byte) (n >> 8 & 0xff);
        bytes[2] = (byte) (n >> 16 & 0xff);
        bytes[3] = (byte) (n >> 24 & 0xff);
        //System.out.println("intToByte before:" + n + ",after:" + Arrays.toString(bytes));
        return bytes;
    }

    public static byte[] shortToByte(short n) {
        //System.out.println("covert:" + n);
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (n & 0xff);
        bytes[1] = (byte) (n >> 8 & 0xff);
        //System.out.println("shortToByte before:" + n + ",after:" + Arrays.toString(bytes));
        return bytes;
    }
}
